#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->regWidget = new RegWidget;

    this->camThread = CameraThread::getInstance();
    this->camThread->videoInit();
    connect(this->camThread, &CameraThread::sendImg, this, &Widget ::receiveImg, Qt::QueuedConnection);
    this->camThread->start();

    connect(this->regWidget, &RegWidget::backToLogin, this, &Widget::RegToLogin);
}

bool Widget::verifyUserByFace(const QString &accessToken, const QString &groupId, const QString &userId, const QByteArray &imgBase64)
{
    //存放返回的数据
    QByteArray replyData;
    QString url = QString(baiduSearchUrl).arg(accessToken);
    //构建请求头
    QMap<QString, QString> header;
    header.insert(QString("Content-Type"), QString("application/json"));

    // 构建请求体
    QJsonObject requestObj;
    requestObj.insert("image", QString(imgBase64));
    requestObj.insert("image_type", "BASE64");
    requestObj.insert("group_id_list", groupId);
    requestObj.insert("quality_control", "NORMAL");
    requestObj.insert("liveness_control", "LOW");
    requestObj.insert("user_id", userId);
    requestObj.insert("match_threshold", 80); // 设置匹配阈值，可以根据需要调整
    //转换为Json格式
    QByteArray requestData = QJsonDocument(requestObj).toJson();

    bool result = BaiduAi::post_sync(url, header, requestData, replyData);

    if(result)
    {
        QJsonObject responseObj = QJsonDocument::fromJson(replyData).object();
        int errorCode = responseObj.value("error_code").toInt();

        if(errorCode == 0)
        {
            QJsonObject resultObj = responseObj.value("result").toObject();
            QJsonArray userList = resultObj.value("user_list").toArray();

            if(!userList.isEmpty())
            {
                QJsonObject userObj = userList.at(0).toObject();
                double score = userObj.value("score").toDouble();

                // 检查匹配得分是否足够高
                if(score >= 80.0) // 可以根据需要调整这个阈值
                {

                    qDebug() << "Face verification successful, score:" << score;
                    return true;
                }
                else
                {
                    qDebug() << "Face verification failed, score too low:" << score;
                }
            }
            else
            {
                qDebug() << "No matching user found";
            }
        }
        else
        {
            QString errorMsg = responseObj.value("error_msg").toString();
            qDebug() << "Face verification failed, error:" << errorCode << errorMsg;
        }
    }
    return false;
}

Widget::~Widget()
{
    delete ui;
}
//去注册界面的槽函数
void Widget::on_pushButton_3_clicked()
{
    this->hide();
    //摄像头先暂停一下
    this->camThread->setIsRun(false);
    this->regWidget->show();
    this->camThread->setIsRun(true);
}

void Widget::RegToLogin()
{
    this->regWidget->close();
    this->show();
}

void Widget::receiveImg(QImage img)
{
    this->img = img;
    update();
}

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    if(!(this->img.isNull()))
    {
        this->img = this->img.scaled(ui->label_3->width(), ui->label_3->height());
        ui->label_3->setPixmap(QPixmap::fromImage(this->img));
    }
}
//登录的槽函数
void Widget::on_pushButton_clicked()
{
    // 保存当前图片用于人脸验证
    QDateTime dateTime = QDateTime::currentDateTime();
    QString str = dateTime.toString("yyyy_MM_dd_hh_mm_ss");
    QString imgPath = "../Photo/login_" + str + ".jpg";
    this->img.save(imgPath);
    qDebug() << "Login image saved to:" << imgPath;

    // 转换为Base64格式
    QByteArray imgBase64 = BaiduAi::ImageToBase64(imgPath);

    // 获取access_token
    QString accessToken = BaiduAi::getAccessToken();
    if(accessToken.isEmpty())
    {
        qDebug() << "Failed to get access token";
        return;
    }

    //获取用户id
    QString userId = ui->lineEdit->text();
    //通过人脸验证用户
    bool result = verifyUserByFace(accessToken, "default_group_id", userId, imgBase64);
    if(result)
    {
        qDebug() << "User successfully verified by face";
        QMessageBox::information(this, "登陆验证", "登陆验证成功");
    }
    else
    {
        qDebug() << "Failed to verify user by face";
         QMessageBox::warning(this, "登陆验证", "登陆验证失败");
        //这里可以添加一下显示错误信息
    }

}
